package com.sqlparser.storage.impl;

import com.sqlparser.storage.Storage;
import com.sqlparser.storage.Table;
import com.sqlparser.common.exception.SQLParserException;

import java.util.*;
import java.text.SimpleDateFormat;

/**
 * 基于内存的存储引擎实现
 */
public class MemoryStorage implements Storage {
    private final Map<String, Table> tables = new HashMap<>();
    
    @Override
    public List<Map<String, Object>> query(String tableName, List<String> columns, String condition) {
        Table table = tables.get(tableName.toLowerCase());
        if (table == null) {
            throw new SQLParserException("Table not found: " + tableName);
        }
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (Map<String, Object> row : table.getRows()) {
            if (evaluateCondition(row, condition)) {
                Map<String, Object> projectedRow = new HashMap<>();
                for (String column : columns) {
                    projectedRow.put(column.toLowerCase(), row.get(column.toLowerCase()));
                }
                result.add(projectedRow);
            }
        }
        
        return result;
    }
    
    @Override
    public int delete(String tableName, String condition) {
        Table table = tables.get(tableName.toLowerCase());
        if (table == null) {
            throw new SQLParserException("Table not found: " + tableName);
        }
        
        List<Map<String, Object>> rows = table.getRows();
        Iterator<Map<String, Object>> iterator = rows.iterator();
        int deletedCount = 0;
        
        while (iterator.hasNext()) {
            Map<String, Object> row = iterator.next();
            if (evaluateCondition(row, condition)) {
                iterator.remove();
                deletedCount++;
            }
        }
        
        return deletedCount;
    }
    
    @Override
    public void initialize() {
        // 创建users表
        List<String> columns = Arrays.asList("id", "name", "age", "salary", "createdate");
        Table usersTable = new Table("users", columns);
        
        // 添加示例数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            usersTable.addRow(new HashMap<String, Object>() {{
                put("id", 1);
                put("name", "John");
                put("age", 25);
                put("salary", 5000.0);
                put("createdate", sdf.parse("2024-01-01"));
            }});
            
            usersTable.addRow(new HashMap<String, Object>() {{
                put("id", 2);
                put("name", "Alice");
                put("age", 30);
                put("salary", 6000.0);
                put("createdate", sdf.parse("2024-01-02"));
            }});
            
            usersTable.addRow(new HashMap<String, Object>() {{
                put("id", 3);
                put("name", "Bob");
                put("age", 18);
                put("salary", 3000.0);
                put("createdate", sdf.parse("2024-01-03"));
            }});
            
        } catch (Exception e) {
            throw new RuntimeException("Failed to initialize data", e);
        }
        
        // 存储表
        tables.put("users", usersTable);
    }
    
    private boolean evaluateCondition(Map<String, Object> row, String condition) {
        if (condition == null || condition.trim().isEmpty()) {
            return true;
        }
        
        // 解析条件字符串，格式：column operator value
        String[] parts = condition.split(" ");
        if (parts.length != 3) {
            throw new SQLParserException("Invalid condition format: " + condition);
        }
        
        String column = parts[0].toLowerCase();
        String operator = parts[1];
        String valueStr = parts[2];
        
        Object rowValue = row.get(column);
        Object conditionValue = parseValue(valueStr, rowValue.getClass());
        
        return compare(rowValue, conditionValue, operator);
    }
    
    @SuppressWarnings("unchecked")
    private boolean compare(Object value1, Object value2, String operator) {
        if (value1 == null || value2 == null) {
            return false;
        }
        
        if (value1 instanceof Comparable) {
            int comparison = ((Comparable) value1).compareTo(value2);
            
            switch (operator) {
                case "=":  return comparison == 0;
                case ">":  return comparison > 0;
                case "<":  return comparison < 0;
                case ">=": return comparison >= 0;
                case "<=": return comparison <= 0;
                case "<>": return comparison != 0;
                default:   throw new SQLParserException("Unsupported operator: " + operator);
            }
        }
        
        throw new SQLParserException("Values cannot be compared: " + value1 + " " + operator + " " + value2);
    }
    
    private Object parseValue(String valueStr, Class<?> targetType) {
        try {
            if (targetType == Integer.class) {
                return Integer.parseInt(valueStr);
            } else if (targetType == Double.class) {
                return Double.parseDouble(valueStr);
            } else if (targetType == Date.class) {
                return new SimpleDateFormat("yyyy-MM-dd").parse(valueStr);
            }
            return valueStr;
        } catch (Exception e) {
            throw new SQLParserException("Failed to parse value: " + valueStr, e);
        }
    }
} 